import random

from django.http import HttpResponse, request
from django.shortcuts import render
# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView
from libs.captcha.captcha import captcha
from django_redis import get_redis_connection

from libs.yuntongxun.sms import CCP
from verifications import serializers

from verifications.serializers import RegisterSmscodeSerializer

#图片验证码
class RegisterImageAPIView(APIView):

    def get(self, request, image_code_id):
        # 1.接收image_code_id
        # 2.生成图片和验证码
        text, image = captcha.generate_captcha()
        # 3.把验证码保存到redis中
        #3.1连接redis
        redis_conn = get_redis_connection('code')
        #3.2设置图片
        redis_conn.setex('img_'+image_code_id, 60, text)
        # 4.返回图片相应
        return HttpResponse(image, content_type='image/jpeg')


#手机验证码
class RegisterSmscodeAPIView(APIView):

    def get(self,request,mobile):
        # 1.接收参数
        params = request.query_params
        # 2.校验参数  还需要验证码 用户输入的图片验证码和redis的保存 是否一致
        serializer = RegisterSmscodeSerializer(data=params)
        serializer.is_valid(raise_exception=True)

        sms_code = '%06d'%random.randint(0, 999999)
        redis_conn = get_redis_connection('code')
        redis_conn.setex('sms_'+mobile, 5*60, sms_code)

        # CCP().send_template_sms(mobile, [sms_code, 5], '1')
        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(mobile, sms_code)

        return Response({'msg':'ok'})
        pass